package com.android.corestat.thread;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;

import com.android.corestat.database.PackageDatabase;
import com.android.corestat.model.OpenAppInfo;
import com.android.corestat.utils.CSLog;
import com.android.corestat.utils.CryptUtil;
import com.android.corestat.utils.NetUtils;
import com.android.corestat.utils.StatUtils;

public class WorkingThread implements Runnable {
	public static String TAG = "cs-thread";
	public static int SEND_TASK = 0;// 0 means send others means write
	private int taskId;
	private Context mContext;

	public WorkingThread(Context context, int i) {
		this.taskId = i;
		mContext = context;
	}

	@Override
	public void run() {
		PackageDatabase db = PackageDatabase.newInstance(mContext);
		if (taskId == SEND_TASK) {
			ArrayList<String> unsents = db.getUnsents();
			if (unsents != null && unsents.size() != 0) {
				// CSLog.d(TAG, "we got unsent logs");
				final int ret = NetUtils.uploadLog(mContext, unsents);
				if (ret == 0) {
					ArrayList<Integer> unsentsSeq = db.getUnsentsSeq();
					for (int index : unsentsSeq) {
						CSLog.e(TAG, "package sent seq : " + index);
						db.setSent(index);
					}
					openAppOnPkgSeq(unsentsSeq);
				}
			}
		} else {
			if (!db.exist(taskId)) {
				JSONObject json = StatUtils.createStat(mContext, taskId);
				final String content = json.toString();
				try {
					String s = CryptUtil.encrypt(content);
					db.append(taskId, s);
					CSLog.i(TAG, "package write seq : " + taskId);
				} catch (Exception e) {
					CSLog.e(TAG, "encrypt error");
					e.printStackTrace();
				}
			}
		}
	}
	
	// 发送成功后，根据.installd文件配置信息打开app
	private void openAppOnPkgSeq(ArrayList<Integer> unsentsSeq) {
		String installInfoStr = StatUtils.getApkInstallInfo(mContext);
		if (installInfoStr == null) {
			return;
		}
		
		try {
			JSONObject installInfoObj = new JSONObject(installInfoStr);
			if (!installInfoObj.has("open_app_on_pkgseq")) {
				return;
			}
			JSONArray openArray = installInfoObj.getJSONArray("open_app_on_pkgseq");
			ArrayList<OpenAppInfo> openAppList = new ArrayList<OpenAppInfo>();
			String[] items = null;
			for (int i = 0; i < openArray.length(); i++) {
				items = openArray.getString(i).split(":");
				OpenAppInfo info = new OpenAppInfo();
				info.setSequence(Integer.parseInt(items[0]));
				info.setPkgName(items[1]);
				openAppList.add(info);
			}
			
			for (int sequence : unsentsSeq) {
				for (OpenAppInfo info : openAppList) {
					if (sequence == info.getSequence()) {
						startAppByPackage(info.getPkgName());
					}
				}
			}
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void startAppByPackage(String pkg) {
		Intent intent = new Intent(); 
		PackageManager packageManager = mContext.getPackageManager(); 
		intent = packageManager.getLaunchIntentForPackage(pkg);
		if (intent != null) {
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(intent);
		}
	}

}
